package controller;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import model.Meal;

public class AddMealBean {
	private String name;
	private String title;
	private String description;
	private String img_url;
	private int price;
	private String type;
	private int active;
	
	private String errors;
	
	public String getErrors(){ return errors; }
	
	public void setErrors( String s ) { errors = s; }
	
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public String getImg_url() {
		return img_url;
	}
	public void setImg_url(String img_url) {
		this.img_url = img_url;
	}
	public int getPrice() {
		return price;
	}
	public void setPrice(int price) {
		this.price = price;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public int getActive() {
		return active;
	}
	public void setActive(int active) {
		this.active = active;
	}
	
	public String add(){
		try {
			validateField(this.name);
			validateField(this.title);
			validateField(this.description);
			validateField(this.img_url);
			validateField(""+this.price);
			validateField(this.type);
		} catch (Exception e) {
			errors = "Hubo un error en uno de los campos";
			return null;
		}
		
		Meal m = new Meal();
		m.setActive(1);
		m.setDescription(description);
		m.setImg_url(img_url);
		m.setName(name);
		m.setPrice(price);
		m.setType(type);
		
		m.register(name, description, img_url, price, title, type);
		
		FacesContext context = FacesContext.getCurrentInstance();
		HttpSession session = (HttpSession) context.getExternalContext().getSession(false);				
		session.setAttribute("message", "Plato agregado exitosamente");
				
		return "success";
	}
	
	private void validateField(String value) throws Exception {
		if ( value == null || value.length() == 0 )
			throw new Exception();
		
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}
